package com.cy.aircompressor.main.home.dialog;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;

import androidx.fragment.app.FragmentManager;
import androidx.lifecycle.Observer;

import com.blankj.utilcode.util.TimeUtils;
import com.cy.aircompressor.databinding.DialogLineChartFullBinding;
import com.cy.aircompressor.entity.linechart.LineChartEntry;
import com.cy.aircompressor.entity.sensor.SensorAgg;
import com.cy.aircompressor.entity.sensor.SensorItemData;
import com.cy.aircompressor.entity.sensor.SensorLineChartData;
import com.cy.aircompressor.entity.sensor.SensorLatestData;
import com.cy.aircompressor.entity.sensor.SensorStatisticsData;
import com.cy.aircompressor.main.home.viewmodel.MainContentViewModel;
import com.cy.aircompressor.main.ui.onlinemonitor.utils.LineChartUtil;
import com.drug.lib.util.DLog;
import com.github.mikephil.charting.data.Entry;
import com.jakewharton.rxbinding2.view.RxView;
import com.net.model.base.Resource;
import com.net.model.base.fragment.BaseVMDialogFragment;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;
import java.util.function.Predicate;
import java.util.stream.Collectors;

public class LineChartFullScreenDialog extends BaseVMDialogFragment<DialogLineChartFullBinding, MainContentViewModel> {
    SensorLineChartData sensorLineChartData;
    private int readyNo = 0;

    public static void showDialogFragment(FragmentManager fragmentManager, String tag, SensorLineChartData sensorLineChartData) {
        Bundle args = new Bundle();
        LineChartFullScreenDialog fragment = new LineChartFullScreenDialog();
        args.putSerializable("sensorLineChartData", sensorLineChartData);
        fragment.setArguments(args);
        fragment.show(fragmentManager, tag);
    }

    @Override
    protected DialogLineChartFullBinding getViewBinding() {
        return DialogLineChartFullBinding.inflate(getLayoutInflater());
    }

    @Override
    protected void initData() {
        sensorLineChartData = (SensorLineChartData) getArguments().getSerializable("sensorLineChartData");
        if (sensorLineChartData == null) dismiss();
        LineChartUtil.initLineChart(mBinding.lineChart, true);
        setDefault();
        setRealTimeData(sensorLineChartData.getSensorLatestData());
        loadLineChart();
        RxView.clicks(mBinding.fullScreen)
                .throttleFirst(500, TimeUnit.MILLISECONDS)
                .subscribe(o -> {
                    dismiss();
                });
    }

    @Override
    protected void requestNetwork() {
        getHandler().postDelayed(loadSensorDataRunnable, 60 * 1000);
    }

    @Override
    protected int getWindowHeight() {
        return getScreenHeight() * 2 / 3;
    }

    @Override
    protected int getWindowWidth() {
        return getScreenWidth() * 2 / 3;
    }

    @Override
    protected void dataChange() {

        mViewModel.getQueryCompressorSensorDataObservable().observe(this, new Observer<Resource<List<SensorLatestData>>>() {
            @Override
            public void onChanged(Resource<List<SensorLatestData>> sensorDataResource) {
                sensorDataResource.handler(new OnCallback<List<SensorLatestData>>() {
                    @Override
                    public void onSuccess(List<SensorLatestData> data) {
                        readyNo++;
                        DLog.e("====数据加载进度=" + readyNo);
                        if (data == null) return;
                        SensorLatestData sensorLatestData = getSensorRealTimeData(sensorLineChartData.getSensorLatestData().getCompressorId(), data);
                        setRealTimeData(sensorLatestData);
                    }
                });
            }
        });


        mViewModel.getQuerySensorStatisticsDataDataObservable().observe(this, new Observer<Resource<List<SensorStatisticsData>>>() {
            @Override
            public void onChanged(Resource<List<SensorStatisticsData>> listResource) {
                listResource.handler(new OnCallback<List<SensorStatisticsData>>() {
                    @Override
                    public void onSuccess(List<SensorStatisticsData> data) {
                        DLog.e("====数据加载进度=" + readyNo);
                        loadLineChart2(data);
                    }
                });
            }
        });
    }

    SensorAgg selectSensor = null;

    private void loadLineChart2(List<SensorStatisticsData> data) {
        if (data != null && data.size() != 0){
            selectSensor = null;
            sensorLineChartData.getSensorAggs().forEach(new Consumer<SensorAgg>() {
                @Override
                public void accept(SensorAgg sensorAgg) {
                    SensorStatisticsData statisticsData = data.get(0);
                    if (TextUtils.equals(statisticsData.getSn(), sensorAgg.getSensor().getSn())) {
                        selectSensor = sensorAgg;
                    }
                }
            });

            if (selectSensor != null) {
                selectSensor.setSensorStatisticsData(data);
                DLog.e("获取传感器数据：" + ",传感器类型：" + selectSensor.getSensor().getCompressorPointCode() + ",传感器数据size:" + data.size());
            }
        }
        readyNo++;
        DLog.e("====数据加载进度=" + readyNo);
        if (readyNo == (sensorLineChartData.getSensorAggs().size() + 1)) {
            DLog.e("====数据加载完成准备刷新=");
            List<LineChartEntry> lineChartEntries = new ArrayList<>();
            for (SensorAgg sensorAgg : sensorLineChartData.getSensorAggs()) {
                List<SensorStatisticsData> sensorStatisticsData = sensorAgg.getSensorStatisticsData();
                if (sensorStatisticsData != null && sensorStatisticsData.size() != 0) {
                    LineChartEntry lineChartEntry = sensorAgg.getLineChartEntry();
                    lineChartEntry.setEntrys(getChartEntry(sensorStatisticsData));
                    String color = getColor(sensorAgg, sensorLineChartData.getPointCode());
                    lineChartEntry.setColor(color);
                    lineChartEntries.add(lineChartEntry);
//                    LineChartUtil.addAndUpdateLine(holder.mBinding.lineChart, lineChartEntry);
                }
            }
            if (lineChartEntries == null || (lineChartEntries != null && lineChartEntries.size() == 0)) {
                LineChartUtil.addEmptyLine(mBinding.lineChart);
            } else {
                LineChartUtil.addAndUpdateLine(mBinding.lineChart, lineChartEntries);
            }

            readyNo = 0;
        }
        LineChartUtil.checkLineChart(mBinding.lineChart);
    }

    private void loadLineChart() {
        if (sensorLineChartData.getSensorAggs() != null) {
            List<LineChartEntry> lineChartEntries = new ArrayList<>();
            for (SensorAgg sensorAgg : sensorLineChartData.getSensorAggs()) {
                List<SensorStatisticsData> sensorStatisticsData = sensorAgg.getSensorStatisticsData();
                if (sensorStatisticsData != null && sensorStatisticsData.size() != 0) {
                    LineChartEntry lineChartEntry = sensorAgg.getLineChartEntry();
                    lineChartEntry.setEntrys(getChartEntry(sensorStatisticsData));
                    String color = getColor(sensorAgg, sensorLineChartData.getPointCode());
                    lineChartEntry.setColor(color);
                    lineChartEntries.add(lineChartEntry);
//                    LineChartUtil.addAndUpdateLine(holder.mBinding.lineChart, lineChartEntry);
                }
            }
            if (lineChartEntries == null || (lineChartEntries != null && lineChartEntries.size() == 0)) {
                LineChartUtil.addEmptyLine(mBinding.lineChart);
            } else {
                LineChartUtil.addAndUpdateLine(mBinding.lineChart, lineChartEntries);
            }
        } else {
            LineChartUtil.addEmptyLine(mBinding.lineChart);
        }
        LineChartUtil.checkLineChart(mBinding.lineChart);
    }

    private List<Entry> getChartEntry(List<SensorStatisticsData> statisticsData) {
        List<Entry> entries = new ArrayList<>();
        if (statisticsData != null && statisticsData.size() != 0) {
            for (int i = 0; i < statisticsData.size(); i++) {
                SensorStatisticsData sensorStatisticsData = statisticsData.get(i);
                try {
                    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    Date date = format.parse(sensorStatisticsData.getRt());
                    Entry entry = new Entry(i, (float) sensorStatisticsData.getV(), date.getTime());
                    entries.add(entry);
                } catch (ParseException e) {
                    e.printStackTrace();
                }
            }
        }
        return entries;
    }

    private String getColor(SensorAgg sensorAgg, String pointCode) {
        String color;
        if (!TextUtils.equals(pointCode, "pressure_water,pressure_oil"))
            color = get1Color(sensorAgg.getSensor().getCompressorPartCode());
        else
            color = get2Color(sensorAgg.getSensor().getCompressorPointCode());
        return color;
    }

    private String get1Color(String partCode) {
        switch (partCode) {
            case "cylinder_1st":
                return "#CF931F";
            case "cylinder_2nd":
                return "#CF1F5E";
            case "cylinder_3rd":
                return "#1F66CF";
            default:
                return "#FFFFFF";
        }
    }

    private String get2Color(String pointCode) {
        switch (pointCode) {
            case "pressure_oil":
                return "#CF931F";
            case "pressure_water":
                return "#CF1F5E";
            default:
                return "#FFFFFF";
        }
    }

    /**
     * 设置默认值
     */
    private void setDefault() {
        switch (sensorLineChartData.getPointCode()) {
            case "temperature":
                mBinding.titleName.setText("温度变化趋势");
                mBinding.textUnit.setText("℃");
                mBinding.labeled1.setText("一级气缸");
                mBinding.labeled2.setText("二级气缸");
                mBinding.labeled3.setText("三级气缸");
                mBinding.labeled3.setVisibility(View.VISIBLE);
                mBinding.labeled3Dot.setVisibility(View.VISIBLE);

                mBinding.cylinder1stName.setText("一级气缸温度");
                mBinding.cylinder1stUnit.setText("℃");
                mBinding.cylinder2stName.setText("二级气缸温度");
                mBinding.cylinder2stUnit.setText("℃");
                mBinding.cylinder3stName.setText("三级气缸温度");
                mBinding.cylinder3stUnit.setText("℃");
                mBinding.cylinder3stLayout.setVisibility(View.VISIBLE);

                break;
            case "pressure":
                mBinding.titleName.setText("压力变化趋势");
                mBinding.textUnit.setText("Mpa");
                mBinding.labeled1.setText("一级气缸");
                mBinding.labeled2.setText("二级气缸");
                mBinding.labeled3.setText("三级气缸");
                mBinding.labeled3.setVisibility(View.VISIBLE);
                mBinding.labeled3Dot.setVisibility(View.VISIBLE);

                mBinding.cylinder1stName.setText("一级气缸压力");
                mBinding.cylinder1stUnit.setText("Mpa");
                mBinding.cylinder2stName.setText("二级气缸压力");
                mBinding.cylinder2stUnit.setText("Mpa");
                mBinding.cylinder3stName.setText("三级气缸压力");
                mBinding.cylinder3stUnit.setText("Mpa");
                mBinding.cylinder3stLayout.setVisibility(View.VISIBLE);
                break;
            case "pressure_water,pressure_oil":
                mBinding.titleName.setText("油压,水压变化趋势");
                mBinding.textUnit.setText("Mpa");
                mBinding.labeled1.setText("油压");
                mBinding.labeled2.setText("水压");
                mBinding.labeled3.setVisibility(View.GONE);
                mBinding.labeled3Dot.setVisibility(View.GONE);

                mBinding.cylinder1stName.setText("油压");
                mBinding.cylinder1stUnit.setText("Mpa");
                mBinding.cylinder2stName.setText("水压");
                mBinding.cylinder2stUnit.setText("Mpa");
                mBinding.cylinder3stLayout.setVisibility(View.GONE);
                break;
        }
    }

    /**
     * 设置最新数据
     *
     * @param sensorLatestData
     */
    private void setRealTimeData(SensorLatestData sensorLatestData) {
        if (sensorLatestData == null) {
            mBinding.cylinder1stValue.setText("-");
            mBinding.cylinder2stValue.setText("-");
            mBinding.cylinder3stValue.setText("-");
        } else {
            String pointCode = sensorLineChartData.getPointCode();
            if (!TextUtils.equals(sensorLineChartData.getPointCode(), "pressure_water,pressure_oil")) {
                SensorItemData sensorItemData = getSensorItemData("cylinder_1st", pointCode, sensorLatestData.getDataList());
                if (sensorItemData == null) {
                    mBinding.cylinder1stValue.setText("-");
                } else {
                    mBinding.cylinder1stValue.setText(sensorItemData.getV());
                }
                sensorItemData = getSensorItemData("cylinder_2nd", pointCode, sensorLatestData.getDataList());
                if (sensorItemData == null) {
                    mBinding.cylinder2stValue.setText("-");
                } else {
                    mBinding.cylinder2stValue.setText(sensorItemData.getV());
                }
                sensorItemData = getSensorItemData("cylinder_3rd", pointCode, sensorLatestData.getDataList());
                if (sensorItemData == null) {
                    mBinding.cylinder3stValue.setText("-");
                } else {
                    mBinding.cylinder3stValue.setText(sensorItemData.getV());
                }
            } else {
                SensorItemData sensorItemData = getSensorItemData("body", "pressure_oil", sensorLatestData.getDataList());
                if (sensorItemData == null) {
                    mBinding.cylinder1stValue.setText("-");
                } else {
                    mBinding.cylinder1stValue.setText(sensorItemData.getV());
                }
                sensorItemData = getSensorItemData("body", "pressure_water", sensorLatestData.getDataList());
                if (sensorItemData == null) {
                    mBinding.cylinder2stValue.setText("-");
                } else {
                    mBinding.cylinder2stValue.setText(sensorItemData.getV());
                }
            }
        }
    }

    private SensorItemData getSensorItemData(String partCode, String pointCode, List<SensorItemData> dataList) {
        if (dataList == null)
            return null;
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
            List<SensorItemData> sensorItemDataList = dataList.stream()
                    .filter(new Predicate<SensorItemData>() {
                        @Override
                        public boolean test(SensorItemData sensorItemData) {
                            return TextUtils.equals(sensorItemData.getCompressorPartCode(), partCode) &&
                                    TextUtils.equals(sensorItemData.getCompressorPointCode(), pointCode);
                        }
                    }).collect(Collectors.toList());
            if (sensorItemDataList != null && sensorItemDataList.size() > 0) {
                return sensorItemDataList.get(0);
            }
        }
        return null;

    }

    private SensorLatestData getSensorRealTimeData(String compressor, List<SensorLatestData> data) {
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
            List<SensorLatestData> sensorLatestDataList = data.stream()
                    .filter(new Predicate<SensorLatestData>() {
                        @Override
                        public boolean test(SensorLatestData sensorRealTimeData) {
                            return TextUtils.equals(sensorRealTimeData.getCompressorId(), compressor);
                        }
                    }).collect(Collectors.toList());
            if (sensorLatestDataList != null && sensorLatestDataList.size() > 0) {
                return sensorLatestDataList.get(0);
            }
        }
        return null;
    }

    /**
     * 查询当前空压机最新数据
     */
    private void queryCompressorNewData() {
        if (TextUtils.isEmpty(sensorLineChartData.getCompressorId())) {
            return;
        }
        List<String> list = new ArrayList<>();
        list.add(sensorLineChartData.getCompressorId());
        mViewModel.queryCompressorSensorRealTimeData(list);
    }


    /**
     * 根据传感器获取传感器统计数据
     */
    private void loadSensorStatisticsData() {
        if (sensorLineChartData.getSensorAggs() == null) {
            return;
        }
        DLog.e("------获取空压机最近一小时数据------");
        DLog.e("------空压机安装传感器数量：------" + sensorLineChartData.getSensorAggs().size());

        long endTime = System.currentTimeMillis();
        long startTime = endTime - (60 * 24 * 60 * 60 * 1000L);
        String pattern = "yyyy-MM-dd HH:mm:ss";
        for (SensorAgg sensorAgg : sensorLineChartData.getSensorAggs()) {
            mViewModel.querySensorStatisticsData(TimeUtils.date2String(new Date(startTime), pattern), TimeUtils.date2String(new Date(endTime), pattern), sensorAgg.getSensor().getSn(), Integer.parseInt(sensorAgg.getSensor().getType()));
        }
        getHandler().postDelayed(loadSensorDataRunnable, 60 * 1000);
    }

    Runnable loadSensorDataRunnable = new Runnable() {
        @Override
        public void run() {
            queryCompressorNewData();
            loadSensorStatisticsData();
        }
    };

    @Override
    public void onDestroy() {
        super.onDestroy();
        getHandler().removeCallbacks(loadSensorDataRunnable);
    }
}
